<?php
header("Content-type: text/xml");
?>
<?xml version="1.0" encoding="UTF-8"?>
<Module>
	<ModulePrefs title="<?php echo $this->platParams['title']?>"
    description="<?php echo $this->platParams['description']?>" 
    author="<?php echo $this->platParams['author']?>" 
    author_email="<?php echo $this->platParams['author_email']?>" 
    screenshot="<?php echo $this->platParams['screenshot']?>"    
    thumbnail="<?php echo $this->platParams['thumbnail']?>" 
    icon="<?php echo $this->platParams['icon']?>">
		<Require feature="opensocial-0.8"/>
		<Require feature="flash"/>
		<Require feature="dynamic-height"/>
		<Require feature="views"/>
	</ModulePrefs>
	<Content type="html" view="canvas">
<![CDATA[
<script type="text/javascript" src="<?php echo $this->webRoot ?>js/xsocialRpc.js"></script>
<script type="text/javascript" src="<?php echo $this->webRoot ?>js/xsocialUI.js"></script>
<div id="xsocial-container"></div>
<script type="text/javascript">
function formatUser(userdata) {
	var ret = {};
	ret.uid = userdata.getId();
	ret.name = userdata.getDisplayName();
	ret.thumbnail = userdata.getField('thumbnailUrl');
	var gender = userdata.getField('gender');
    if (gender == null) {
        ret.gender = null;
    } else {
        ret.gender = gender.key == 'MALE' ? 1 : 0;
    }
	ret.birthday = userdata.getField('birthday');
	return ret;
}

var xsocialApi = {
    init : function() {
        xsocialApi.friends = [];
        xsocialApi.makeSig();
    },
    
    makeSig : function() {
        xsocialApi.signRequest('<?php echo $this->canvasPath ?>?action=makeSig',function(data) {
            var data = data.data;
            xsocialApi.uid = data.uid;
            xsocialApi.sessionkey = data.sessionkey;
            xsocialApi.sig = data.sig;
            initRpc();
        });
    },
    
    getViewer : function(callback) {
        if (xsocialApi.viewer) {
            if (callback) callback(xsocialApi.viewer);
            return;
        }
        var req = opensocial.newDataRequest();
		var params = {};
		params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.GENDER,opensocial.Person.Field.BIRTHDAY];
		req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER, params), 'viewer');
        
        req.send(function(data) {
            var userdata = data.get('viewer').getData();
            xsocialApi.viewer = formatUser(userdata);
            if (callback) callback(xsocialApi.viewer);
        });
    },
    
	getFriends : function(callback,opt) {
		if (xsocialApi.friends != null && xsocialApi.friends.length != 0) {
            if (callback) callback(xsocialApi.friends);
            return;
        }
		xsocialApi.getFriendsByPage(xsocialApi.friends,callback,{"first":0,"max":100});
		
	},
	
    getFriendsByPage : function(friends,callback,opt) {
		opt = opt || {};
		opt.first = opt.first || 0;
		opt.max = opt.max || 100;
        var req = opensocial.newDataRequest();
        var ownerFriends = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" }); 
		var params = {};
		params[opensocial.DataRequest.PeopleRequestFields.FIRST] = opt.first;
		params[opensocial.DataRequest.PeopleRequestFields.MAX] = opt.max;
		params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.GENDER, opensocial.Person.Field.BIRTHDAY];
		req.add(req.newFetchPeopleRequest(ownerFriends, params), "friends");
        req.send(function(data) {
            var friendsData = data.get('friends').getData();
            var total = data.get('friends').getData().getTotalSize();
			//console.log(friendsData);
			friendsData.each(function(person) {
				friends.push(formatUser(person));
			});
			if (opt.first + opt.max >= total) {
				if(callback) callback(friends);
			} else {
				opt.first = opt.first + opt.max;
				xsocialApi.getFriendsByPage(friends,callback,opt);
			}
        });
    },
    
    invite : function(bundleData, callback) {
        bundleData = {title:"Invite Test",content:"Invite content"};
		xsocialApi.getFriends(
		    function(friends) {
		        xsocialUI.createWindow({
                    title : bundleData.title,
                    content : xsocialUI.friendsSelector(friends),
					onclose : function(result) {
						//do nothing
					}
		        });
		    }
		);
		
		xsocialUI.onFriendClick = function(id) {
			var title = bundleData.title || "";
			var body = bundleData.content || "";
			var params = [];
			params[opensocial.Message.Field.TITLE] = title;
			params[opensocial.Message.Field.TYPE] = opensocial.Message.Type.EMAIL;
			var message = opensocial.newMessage(body, params);
			opensocial.requestSendMessage(id, message,function(data) {
				if (data.hadError()) {
					alert("There was a problem:" + data.getErrorCode());
				}else {
					if (callback) callback(id);
				}
			});
		};
		
    },
    payment : function() {
        alert("payment not implemented.");
    },
    adjustHeight : function() {
		gadgets.window.adjustHeight();
    },
    post : function(bundleData, callback) {
        var params = {};  
        params[opensocial.Activity.Field.TITLE] = bundleData.title;
        params[opensocial.Activity.Field.BODY] = bundleData.content;
        var activity = opensocial.newActivity(params);
        opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function(status) {
            if (status.hadError()) {
                if (callback) callback({error:true,message:status.getErrorMessage()});
            }else {
                if (callback) callback({error:false});
            }
        });
    },
        
    signRequest : function(url,callback,requestParams) {
        var params = {};
		params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		if(requestParams)
		{
			params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(requestParams);
		}
		gadgets.io.makeRequest(
				url, 
				function(data)
				{	
					if(callback) {
						// Fix for IE
						for (var a in data) {
							if (data.hasOwnProperty(a)) {
								if(typeof data[a] == 'undefined') {
									data[a] = 'undefined';
								}
							}
						}
						callback(data);
					}
				}, 
				params);
    }
};

//var xsocialApi = xsocialTestApi;
</script>
<script>
var ifrSrc = "<?php echo $this->appIframeUrl ?>";
xsocialApi.init();
</script>

	]]>
	</Content>
</Module>